/**
 * @Description: 请求封装
 * @Author: zhen
 * @Date: 2023-10-18
 */
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import { globalI18N } from '@/locales';
import { BASE_API_URL } from '@/constants';
import { getToken, removeToken, setToken } from '@/utils/auth';
import { APIResponse } from './types';

export const httpInstance = axios.create({
  baseURL: BASE_API_URL,
  timeout: 300000 // 默认超时时间
  // 验证请求状态
  // validateStatus(status) {
  //   // return status >= 200 && status < 300; // 默认的
  //   return status < 400
  // }
});

// 请求拦截器
httpInstance.interceptors.request.use((config) => {
  const token = getToken();
  if (token) {
    config.headers.Authorization = token;
  }
  return config;
});

// 相应拦截器
httpInstance.interceptors.response.use((response) => {
  // refresh access token
  const token = response.headers.authorization;
  if (token) {
    setToken(token);
  }
  return response;
});

/**
 * 请求方法
 * @template T
 * @param {(string | AxiosRequestConfig)} url // 请求路径
 * @param {AxiosRequestConfig} [config] // 请求配置
 * @param {{
 *     onFulfilled?: (value: AxiosResponse<any>) => APIResponse<T>; // 自定义请求通过处理
 *     onRejected?: (error) => any; // 自定义请求拒绝处理
 *   }} [extra]
 * @return {*}  {Promise<APIResponse<T>>}
 */
export function request<T>(
  url: string | AxiosRequestConfig,
  config?: AxiosRequestConfig,
  extra?: {
    onFulfilled?: (value: AxiosResponse<any>) => APIResponse<T>;
    onRejected?: (error: any) => any;
  }
): Promise<APIResponse<T>> {
  const defaultFulfilled = (response: { data: APIResponse<T> }) => response.data as APIResponse<T>;
  const defaultRejected = (error: any) => {
    throw standardErrorMessageTransformer(error);
  };
  const axiosPromise = typeof url === 'string' ? httpInstance(url, config) : httpInstance(url);
  return axiosPromise
    .then(extra?.onFulfilled || defaultFulfilled, unAuthorizationErrorHandler)
    .catch(extra?.onRejected || defaultRejected);
}

// 使用header配置的请求
export function requestWithHeader(url: string | AxiosRequestConfig, config?: AxiosRequestConfig) {
  return request(url, config, {
    onFulfilled: (response: { data: any; headers: any }) => {
      return [response.data, response.headers] as any;
    }
  }) as any;
}

// 获取服务地址
export const getServerDomain = () => {
  return `${window.location.protocol}//${window.location.host}`;
};

// 未验证错误信息处理
function unAuthorizationErrorHandler(error: { response: { status: number } }) {
  if (error?.response?.status === 401) {
    ElMessage.error(globalI18N.t('global.error.401'));
    removeToken();
    return true;
  }
  throw error;
}

// 标准错误信息转化
function standardErrorMessageTransformer(error: { response: { data: { message: any } } }) {
  if (error?.response?.data?.message) {
    return error?.response?.data?.message;
  }
  return error;
}
